package spike.s002.time.timezone.service;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

/**
 * Created by ylyang on 11/04/2017.
 */
public class TimeUtils {
    public static final String TIME_ZONE_ERROR_EXCEPTION = "TIME ZONE ERROR EXCEPTION.";

    private static TimeZone calcTimeZoneWithMs(int ms) {
        String[] ids = TimeZone.getAvailableIDs(ms);
        if (ids.length == 0) {
            throw new RuntimeException(TIME_ZONE_ERROR_EXCEPTION);
        } else {
            return new SimpleTimeZone(ms, ids[0]);
        }
    }

    public static SimpleDateFormat createSDF(int ms, String pattern) {
        return new SimpleDateFormat(pattern) {{
            setTimeZone(calcTimeZoneWithMs(ms));
        }};
    }

    /**
     * Created by ylyang on 02/03/2017.
     */
    public static class D2S {
        public static String convertD2UTCS(Date date, String pattern) {
            return convertD2S(date, 0, pattern);
        }

        public static String convertD2S(Date date, int ms, String pattern) {
            return convertD2S(date, createSDF(ms, pattern));
        }

        public static String convertD2S(Date date, SimpleDateFormat sdf) {
            return sdf.format(date);
        }
    }

    /**
     * Created by ylyang on 10/04/2017.
     */
    public static class S2D {
        public static Date convertS2UTCD(String strDate, String pattern) throws ParseException {
            return convertS2D(strDate, 0, pattern);
        }

        public static Date convertS2D(String strDate, int ms, String pattern) throws ParseException {
            return convertS2D(strDate, createSDF(ms, pattern));
        }

        public static Date convertS2D(String strDate, SimpleDateFormat sdf) throws ParseException {
            return sdf.parse(strDate);
        }
    }

    /**
     * Created by ylyang on 30/03/2017.
     */
    public static enum DatePattern {
        YMDHMS("yyyy-MM-dd HH:mm:ss"),
        YMD("yyyy-MM-dd"),

        DEFAULT_PATTERN(YMDHMS.strDatePattern);

        private String strDatePattern;

        DatePattern(String strDatePattern) {
            this.strDatePattern = strDatePattern;
        }

        @Override
        public String toString() {
            return strDatePattern;
        }
    }

    public static class JodaTime {
        public static String convertD2S(Date date, int ms, String pattern) {
            return (new DateTime(date.getTime()).withZone(DateTimeZone.forOffsetMillis(ms))).toString(pattern);
        }

        public static Date convertS2D(String strDate, int ms, String pattern) {
            return DateTime.parse(strDate, DateTimeFormat.forPattern(pattern).withZone(DateTimeZone.forOffsetMillis(ms))).toDate();
        }
    }
}
